"""
解析出某一块日志中的数据
"""
from typing import Iterator, Tuple, Any
import re
from exception import ParseException
from service import regex_service
from enums import ErrorLogType


def parse_request_field(line_iter: Iterator[str]) -> Tuple[str, str]:
    """
    解析请求域中的数据
    :param line_iter: 文本行的迭代器
    :return: (请求的类型, 请求的地址)
    """
    line = next(line_iter)
    req_pattern = re.compile('(?<====>).*(?=Parameters:.*)')
    req_api = re.search(req_pattern, line)
    if req_api is None:
        raise ParseException('解析 Request 部分出现异常')
    req_api = req_api.group().strip()
    req_type, req_addr = req_api.split(':')

    while True:
        if regex_service.is_request_end(line):
            break
        else:
            line = next(line_iter)
    return req_type, req_addr.strip()


def parse_response_field(line_iter: Iterator[str]) -> Tuple[str, str]:
    """
    解析响应域中的数据
    :param line_iter: 文本行的迭代器
    :return: (请求的类型, 请求的地址)
    """
    resp_info_pattern = re.compile(r'(?<=<===).*(?=\(\d+\s+ms\))')
    resp_api = None
    req_type = None
    req_addr = None
    while True:
        line = next(line_iter)
        if regex_service.is_response_end(line):
            break
        search_result = re.search(resp_info_pattern, line)
        if search_result is None:
            continue
        else:
            resp_api = search_result.group().strip()
            req_type, req_addr = resp_api.split(':')
            continue

    if resp_api is None:
        raise ParseException('解析 Request 部分出现异常')
    # 读出响应域中剩余的行
    while True:
        if regex_service.is_response_end(line):
            break
        else:
            line = next(line_iter)
    return req_type, req_addr.strip()


def parse_error_log(line: str) -> Tuple[ErrorLogType, Any]:
    """
    解析错误的日志
    :param line: 所要解析的日志行
    :return:
    """
    if regex_service.is_undertow_request_log(line):  # 是否是 Servlet path match failed
        return ErrorLogType.SERVLET_PATH_MATCH_FAILED, None
    if regex_service.is_404_error_log(line):  # 是否是 404 错误的行
        return ErrorLogType.NOT_FOUNT_ERROR, None
    if regex_service.is_token_error_log(line):  # 是否是 token error 的行
        return ErrorLogType.TOKEN_ERROR, None
    if regex_service.is_dfmc_exception_log(line):
        return ErrorLogType.DFMC_EXCEPTION, None
    print(line)
    return ErrorLogType.OTHER, None
